package com.tangyee.home_blood_center.fragments;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tangyee.home.activity.db.UsersInfo;
import com.tangyee.home_blood_center.bean.BSRecord;
import com.tangyee.home_blood_center.db.BSRecordHolder;
import com.tangyee.home_blood_center.utils.DateUtil;
import com.tangyee.home_blood_center.utils.DialogUtils;
import com.tangyee.home_blood_center.utils.EditInputFilter;
import com.tangyee.R;
import com.tangyee.home_blood_center.bean.BSRecord;
import com.tangyee.home_blood_center.db.BSRecordHolder;
import com.tangyee.home_blood_center.utils.DateUtil;
import com.tangyee.home_blood_center.utils.EditInputFilter;
import com.tangyee.utils.UserInfoUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 和AddBloodPressureRecordFragment差不多，不多写注释了
 */
public class AddBloodSugarRecordFragment extends BaseFragment {

    private BSRecord mBSRecord;

    private EditText mEditText;
    private TextView mTextView0;
    private TextView mTextView1;
    private TextView mTextView2;
    private TextView mTextView3;
    private TextView mTextView4;
    private TextView mTextView5;
    private TextView mTextView6;
    private TextView mTextView7;

    private List<TextView> mTextViews;

    private ImageView left;
    private TextView middleTV;
    private ImageView middle;
    private TextView right;

    private Button reset;

    private String text;

    private long value;

    private int sign;

    private boolean isSave;

    private UsersInfo mUsersInfo = UserInfoUtil.getLoadedUser();
    private String sessionid = mUsersInfo.getSessionid();
    private String cookie = "ASP.NET_SessionId=" + sessionid;

    private Dialog dialog = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        value = getArguments().getLong("value");
    }

    public static AddBloodSugarRecordFragment newInstance(long value){
        Bundle bundle = new Bundle();
        bundle.putLong("value",value);
        AddBloodSugarRecordFragment addBloodSugarRecordFragment = new AddBloodSugarRecordFragment();
        addBloodSugarRecordFragment.setArguments(bundle);
        return addBloodSugarRecordFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_blood_sugar_record, container, false);
        BSRecord bsRecord = BSRecordHolder.get(getContext()).getRSRecordByTime(value / 10);
        if (bsRecord == null) throw new RuntimeException("没找到记录：" + value / 10);
        sign = (int) (value % 10);
        mBSRecord = bsRecord;
        text = "" + mBSRecord.getDataBySign(sign);

        left = view.findViewById(R.id.btn_top_left);
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        middleTV = view.findViewById(R.id.tv_center);
        middleTV.setText(DateUtil.date2Str(mBSRecord.getDate(), "MM月dd日") + "  " + DateUtil.getTimeDescription(sign));
        middle = view.findViewById(R.id.down);
        middle.setVisibility(View.GONE);
        right = view.findViewById(R.id.btn_top_right);
        right.setText("保存");
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSave = true;
                dialog = DialogUtils.createLoadingDialog(getActivity(), "努力保存中...");
                mBSRecord.setDataBySign(sign, Double.parseDouble(text));
                new SaveBSRecord(mBSRecord).execute();
//                getActivity().onBackPressed();
            }
        });

        mEditText = view.findViewById(R.id.BloodSugarEditText);
        // 输入过滤
        mEditText.setFilters(new InputFilter[]{
                new EditInputFilter(18, getContext())
        });
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // This space intentionally left blank
            }

            @SuppressLint("ResourceAsColor")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    text = "" + mBSRecord.getDataBySign(sign);
                } else {
                    text = s.toString();

                    // 点击消失的动画（如果系统支持 api>=21）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        int cx = reset.getWidth() / 2;
                        int cy = reset.getHeight() / 2;
                        float radius = reset.getWidth();
                        Animator anim = ViewAnimationUtils.createCircularReveal(reset, cx, cy, 0, radius);
                        anim.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                reset.setVisibility(View.VISIBLE);
                            }
                        });
                        anim.start();
                    } else { // 不支持动画，则直接设置不可见
                        reset.setVisibility(View.VISIBLE);
                        reset.setBackgroundColor(R.color.bgColor);
                        reset.setTextColor(Color.GRAY);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                // this one too
            }
        });
        mTextView0 = view.findViewById(R.id.textView0);
        mTextView1 = view.findViewById(R.id.textView1);
        mTextView2 = view.findViewById(R.id.textView2);
        mTextView3 = view.findViewById(R.id.textView3);
        mTextView4 = view.findViewById(R.id.textView4);
        mTextView5 = view.findViewById(R.id.textView5);
        mTextView6 = view.findViewById(R.id.textView6);
        mTextView7 = view.findViewById(R.id.textView7);
        mTextViews = new ArrayList<>();
        mTextViews.add(mTextView0);
        mTextViews.add(mTextView1);
        mTextViews.add(mTextView2);
        mTextViews.add(mTextView3);
        mTextViews.add(mTextView4);
        mTextViews.add(mTextView5);
        mTextViews.add(mTextView6);
        mTextViews.add(mTextView7);
        for (int i = 0; i < mTextViews.size(); i ++) {
            mTextViews.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int j = 0; j < mTextViews.size(); j ++) {
                        mTextViews.get(j).setBackgroundResource(R.color.arc_inteval);
                        mTextViews.get(j).setTextColor(getResources().getColor(R.color.blood_center_text_color));
                    }
                    v.setBackgroundColor(getResources().getColor(R.color.fill));
                    ((TextView)v).setTextColor(Color.BLACK);
                    updateSign();
                }
            });
            if (i == sign - 1) {
                mTextViews.get(i).setBackgroundColor(getResources().getColor(R.color.fill));
                mTextViews.get(i).setTextColor(Color.BLACK);
            }
        }

        mEditText.setHint("" + mBSRecord.getDataBySign(sign));

        reset = view.findViewById(R.id.reset_btn);
        reset.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onClick(View v) {
                // 点击消失的动画（如果系统支持 api>=21）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    int cx = reset.getWidth() / 2;
                    int cy = reset.getHeight() / 2;
                    float radius = reset.getWidth();
                    Animator anim = ViewAnimationUtils.createCircularReveal(reset, cx, cy, radius, 0);
                    anim.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            reset.setVisibility(View.INVISIBLE);
                        }
                    });
                    anim.start();
                } else { // 不支持动画，则直接设置不可见
                    reset.setVisibility(View.INVISIBLE);
                    reset.setBackgroundColor(R.color.bgColor);
                    reset.setTextColor(Color.GRAY);
                }
                for (int i = 0; i < mTextViews.size(); i ++){
                    if (((ColorDrawable)mTextViews.get(i).getBackground()).getColor() == getResources().getColor(R.color.fill)){
                        sign = i + 1;
                        mEditText.setText("");
                        text = "" + mBSRecord.getDataBySign(sign);
                        mEditText.setHint(text);
                    }
                }
            }
        });

        return view;
    }

    private void updateSign() {
        mBSRecord.setDataBySign(sign, Double.parseDouble(text));
        for (int i = 0; i < mTextViews.size(); i ++){
            if (((ColorDrawable)mTextViews.get(i).getBackground()).getColor() == getResources().getColor(R.color.fill)){
                sign = i + 1;
                mEditText.setText("");
                text = "" + mBSRecord.getDataBySign(sign);
                mEditText.setHint(text);
                middleTV.setText(DateUtil.date2Str(mBSRecord.getDate(), "MM月dd日") + "  " + DateUtil.getTimeDescription(sign));
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private class SaveBSRecord extends AsyncTask<Void, Void, String[]> {

        private static final String TAG = "SaveBSRecord";
        private BSRecord bsRecord;
        private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        public SaveBSRecord(BSRecord record) {
            this.bsRecord = record;
            Log.d(TAG, "SaveBSRecord: " + record.toString());
        }

        @Override
        protected String[] doInBackground(Void... voids) {
            String r = null;
            OkHttpClient okHttpClient = new OkHttpClient();

            String d = dateFormat.format(bsRecord.getDate());
            Log.d(TAG, "doInBackground: " + d);
            RequestBody body1 = new FormBody.Builder()
                    .add("recordDate",  d)
                    .add("timePoint", "MBG")
                    .add("mValue", String.valueOf(bsRecord.getDataBySign(1)))
                    .build();
            Request request1 = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/SetBloodGlucose")
                    .addHeader("cookie", cookie)
                    .post(body1)
                    .build();

            RequestBody body2 = new FormBody.Builder()
                    .add("recordDate",  d)
                    .add("timePoint", "BBFBG")
                    .add("mValue", String.valueOf(bsRecord.getDataBySign(2)))
                    .build();
            Request request2 = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/SetBloodGlucose")
                    .addHeader("cookie", cookie)
                    .post(body2)
                    .build();

            RequestBody body3 = new FormBody.Builder()
                    .add("recordDate",  d)
                    .add("timePoint", "ABFBG")
                    .add("mValue", String.valueOf(bsRecord.getDataBySign(3)))
                    .build();
            Request request3 = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/SetBloodGlucose")
                    .addHeader("cookie", cookie)
                    .post(body3)
                    .build();

            RequestBody body4 = new FormBody.Builder()
                    .add("recordDate",  d)
                    .add("timePoint", "BLBG")
                    .add("mValue", String.valueOf(bsRecord.getDataBySign(4)))
                    .build();
            Request request4 = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/SetBloodGlucose")
                    .addHeader("cookie", cookie)
                    .post(body4)
                    .build();

            RequestBody body5 = new FormBody.Builder()
                    .add("recordDate",  d)
                    .add("timePoint", "ALBG")
                    .add("mValue", String.valueOf(bsRecord.getDataBySign(5)))
                    .build();
            Request request5 = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/SetBloodGlucose")
                    .addHeader("cookie", cookie)
                    .post(body5)
                    .build();

            RequestBody body6 = new FormBody.Builder()
                    .add("recordDate",  d)
                    .add("timePoint", "BDBG")
                    .add("mValue", String.valueOf(bsRecord.getDataBySign(6)))
                    .build();
            Request request6 = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/SetBloodGlucose")
                    .addHeader("cookie", cookie)
                    .post(body6)
                    .build();

            RequestBody body7 = new FormBody.Builder()
                    .add("recordDate",  d)
                    .add("timePoint", "ADBG")
                    .add("mValue", String.valueOf(bsRecord.getDataBySign(7)))
                    .build();
            Request request7 = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/SetBloodGlucose")
                    .addHeader("cookie", cookie)
                    .post(body7)
                    .build();

            RequestBody body8 = new FormBody.Builder()
                    .add("recordDate",  d)
                    .add("timePoint", "BTBG")
                    .add("mValue", String.valueOf(bsRecord.getDataBySign(8)))
                    .build();
            Request request8 = new Request.Builder()
                    .url("https://www.tangyee.com/Mobile/Health/SetBloodGlucose")
                    .addHeader("cookie", cookie)
                    .post(body8)
                    .build();

            try {
                Response response1 = okHttpClient.newCall(request1).execute();
                Response response2 = okHttpClient.newCall(request2).execute();
                Response response3 = okHttpClient.newCall(request3).execute();
                Response response4 = okHttpClient.newCall(request4).execute();
                Response response5 = okHttpClient.newCall(request5).execute();
                Response response6 = okHttpClient.newCall(request6).execute();
                Response response7 = okHttpClient.newCall(request7).execute();
                Response response8 = okHttpClient.newCall(request8).execute();
                return new String[]{
                        response1.body().string(),
                        response2.body().string(),
                        response3.body().string(),
                        response4.body().string(),
                        response5.body().string(),
                        response6.body().string(),
                        response7.body().string(),
                        response8.body().string()
                };
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] strings) {
            boolean result = true;
            if (strings == null) {
                result = false;
            } else {
                for (String s : strings) {
                    if (!"\"1\"".equals(s)) {
                        Log.d(TAG, s);
                        result = false;
                        break;
                    }
                }
            }
            if (result) {
                BSRecordHolder.get(getContext()).updateDate(bsRecord);
                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), "保存失败，服务器繁忙。", Toast.LENGTH_SHORT).show();
            }
            DialogUtils.closeDialog(dialog);
            getActivity().onBackPressed();
        }
    }

}
